<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    title="关联房户"
    width="1000px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="associate-household-dialog">
      <!-- 业主信息展示 -->
      <el-card class="owner-info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">业主信息</span>
          </div>
        </template>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="业主姓名">{{ ownerData?.ownerName }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ ownerData?.idCard }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ ownerData?.phone }}</el-descriptions-item>
          <el-descriptions-item label="邮箱地址">{{ ownerData?.email || '-' }}</el-descriptions-item>
          <el-descriptions-item label="性别">
            <el-tag :type="ownerData?.gender === 1 ? 'primary' : ownerData?.gender === 2 ? 'success' : 'info'">
              {{ ownerData?.gender === 1 ? '男' : ownerData?.gender === 2 ? '女' : '未知' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="ownerData?.status === 1 ? 'success' : 'danger'">
              {{ ownerData?.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 房户选择区域 -->
      <el-card class="household-selector-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">选择房户</span>
            <span class="card-subtitle">请选择要关联的房户</span>
          </div>
        </template>
        <HouseholdSelector
          v-model="householdSelector"
          @change="handleHouseholdChange"
        />
      </el-card>

      <!-- 关联信息设置 -->
      <el-card class="association-info-card" shadow="never" v-if="householdSelector.householdId">
        <template #header>
          <div class="card-header">
            <span class="card-title">关联信息</span>
            <span class="card-subtitle">设置关联的详细信息</span>
          </div>
        </template>
        
        <el-form
          ref="associationFormRef"
          :model="associationForm"
          :rules="associationRules"
          label-width="120px"
          label-position="right"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="产权类型" prop="ownershipType">
                <el-select v-model="associationForm.ownershipType" placeholder="请选择产权类型" style="width: 100%">
                  <el-option label="完全产权" :value="1" />
                  <el-option label="共有产权" :value="2" />
                  <el-option label="部分产权" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产权比例" prop="ownershipRatio">
                <el-input-number
                  v-model="associationForm.ownershipRatio"
                  :min="0"
                  :max="100"
                  :precision="2"
                  style="width: 100%"
                />
                <span style="margin-left: 8px;">%</span>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="是否主业主" prop="isPrimaryOwner">
                <el-radio-group v-model="associationForm.isPrimaryOwner">
                  <el-radio :label="true">是</el-radio>
                  <el-radio :label="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房产证号" prop="certificateNumber">
                <el-input
                  v-model="associationForm.certificateNumber"
                  placeholder="请输入房产证号"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="房产证日期" prop="certificateDate">
                <el-date-picker
                  v-model="associationForm.certificateDate"
                  type="date"
                  placeholder="请选择房产证日期"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注信息" prop="remark">
                <el-input
                  v-model="associationForm.remark"
                  placeholder="请输入备注信息"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit" 
          :loading="submitLoading"
          :disabled="!householdSelector.householdId"
        >
          确定关联
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { ownerHouseholdApi, type OwnerHouseholdDTO } from '@/api/ownerHousehold'
import HouseholdSelector from './HouseholdSelector.vue'

// 定义组件属性
interface Props {
  visible: boolean
  ownerData?: any
}

// 定义组件事件
interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 表单引用
const associationFormRef = ref<FormInstance>()

// 提交加载状态
const submitLoading = ref(false)

// 房户选择器数据
const householdSelector = reactive({
  communityId: undefined as number | undefined,
  buildingId: undefined as number | undefined,
  unitId: undefined as number | undefined,
  householdId: undefined as number | undefined
})

// 关联表单数据
const associationForm = reactive({
  ownershipType: 1,
  ownershipRatio: 100,
  isPrimaryOwner: true,
  certificateNumber: '',
  certificateDate: undefined as string | undefined,
  remark: ''
})

// 表单验证规则
const associationRules: FormRules = {
  ownershipType: [
    { required: true, message: '请选择产权类型', trigger: 'change' }
  ],
  ownershipRatio: [
    { required: true, message: '请输入产权比例', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '产权比例必须在0-100之间', trigger: 'blur' }
  ],
  isPrimaryOwner: [
    { required: true, message: '请选择是否主业主', trigger: 'change' }
  ]
}

// 监听房户选择变化
const handleHouseholdChange = (value: any) => {
  console.log('房户选择变化:', value)
}

// 提交表单
const handleSubmit = async () => {
  if (!props.ownerData || !householdSelector.householdId) {
    ElMessage.error('请选择要关联的房户')
    return
  }
  
  if (!associationFormRef.value) {
    return
  }
  
  try {
    // 验证表单
    await associationFormRef.value.validate()
    
    submitLoading.value = true
    
    // 构建提交数据
    const submitData: OwnerHouseholdDTO = {
      ownerId: props.ownerData.id,
      householdId: householdSelector.householdId,
      ownershipType: associationForm.ownershipType,
      ownershipRatio: associationForm.ownershipRatio,
      isPrimaryOwner: associationForm.isPrimaryOwner,
      certificateNumber: associationForm.certificateNumber || undefined,
      certificateDate: associationForm.certificateDate,
      remark: associationForm.remark || undefined
    }
    
    // 调用API
    const response = await ownerHouseholdApi.createOwnerHousehold(submitData)
    
    if (response.code === 200) {
      ElMessage.success('关联房户成功')
      emit('success')
      handleCancel()
    } else {
      ElMessage.error(response.message || '关联房户失败')
    }
  } catch (error) {
    console.error('关联房户失败:', error)
    ElMessage.error('关联房户失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  // 重置表单
  if (associationFormRef.value) {
    associationFormRef.value.resetFields()
  }
  
  // 重置房户选择器
  if (householdSelector) {
    householdSelector.communityId = undefined
    householdSelector.buildingId = undefined
    householdSelector.unitId = undefined
    householdSelector.householdId = undefined
  }
  
  // 重置关联表单数据
  Object.assign(associationForm, {
    ownershipType: 1,
    ownershipRatio: 100,
    isPrimaryOwner: true,
    certificateNumber: '',
    certificateDate: undefined,
    remark: ''
  })
  
  emit('update:visible', false)
}

// 监听对话框显示状态，重置表单
watch(() => props.visible, (newVal) => {
  if (!newVal) {
    handleCancel()
  }
})
</script>

<style lang="scss" scoped>
.associate-household-dialog {
  .owner-info-card,
  .household-selector-card,
  .association-info-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      align-items: center;
      
      .card-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        margin-right: 8px;
      }
      
      .card-subtitle {
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input),
:deep(.el-select),
:deep(.el-date-picker),
:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number) {
  .el-input__wrapper {
    width: 100%;
  }
}
</style>
